//
// Created by LiuYou on 2021/8/4.
//

#include <cstdio>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstring>
#include "Proto.hpp"


int main(int argc, char** argv) {
    if (argc < 3) {
        fprintf( stderr, "Usage...\n" );
        exit( 1 );
    }
    if (strlen( argv[2] ) > NAME_MAX) {
        fprintf( stderr, "Name is too long!\n" );
        exit( 1 );
    }

    int socketFD = socket( PF_INET, SOCK_DGRAM, 0 );
    if (socketFD < 0) {
        perror( "socket()" );
        exit( 1 );
    }

    // bind()在主动端可以不使用。
//    bind();

    using SocketBasic::Msg;
//    Msg sendMsg( "Alan", htonl((rand() % 100)), htonl((rand() % 100)));
    Msg* ptrSendMsg;
    size_t msgSize = sizeof( Msg ) + strlen( argv[2] );
    void* pVoid = malloc( msgSize );
    ptrSendMsg = static_cast<Msg*>(pVoid);
    if (ptrSendMsg == nullptr) {
        perror( "malloc()" );
        exit( 1 );
    }
    strcpy((char*) ptrSendMsg->name, argv[2] );
    ptrSendMsg->math = htonl((rand() % 100));
    ptrSendMsg->chinese = htonl((rand() % 100));
    struct sockaddr_in remoteAddress{
            .sin_family=AF_INET,
            .sin_port=htons( atoi( RCV_PORT ))
    };
    inet_pton( AF_INET, argv[1], &remoteAddress.sin_addr );
    ssize_t ret = sendto( socketFD, ptrSendMsg, msgSize, 0,
                          (sockaddr*) &remoteAddress, sizeof( remoteAddress ));
    if (ret < 0) {
        perror( "sendto()" );
        exit( 1 );
    }
    puts( "OK!" );
    free( pVoid );
    close( socketFD );

    exit( 0 );
}